package dimension.stock;

import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

public class Command implements CommandExecutor {

    @Override
    public boolean onCommand(CommandSender sender, org.bukkit.command.Command command,String label, String[] args) {
        if (!"dst".equalsIgnoreCase(command.getName())) {
            return true;
        }

        if(args.length == 0){
            displayHelp(sender);
        } else if (args.length == 1 && "price".equals(args[0])) {
            BigDecimal latestPrice = Exchanger.getLatestPrice();
            BigDecimal rate = latestPrice.subtract(Exchanger.getLastDayPrice()).divide(Exchanger.getLastDayPrice(),RoundingMode.HALF_UP).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
            boolean isDown = rate.compareTo(BigDecimal.ZERO) < 0;
            sender.sendMessage(MainClass.PREFIX + " §7股票 §f哈基ETF" + " §7最新成交价为 §a" + latestPrice.setScale(2,RoundingMode.HALF_UP) + " §7当日涨跌幅 §" + (isDown?"a":"c") + rate + "%");
        } else if (args.length == 1 && "all".equals(args[0])) {
            displayAllHaveStock(sender);
        } else if (args.length == 2 && "buy".equals(args[0])) {
            Exchanger.buy(sender,Long.parseLong(args[1]));
        } else if (args.length == 2 && "sell".equals(args[0])) {
            Exchanger.sell(sender,Long.parseLong(args[1]));
        } else if (args.length == 1 && "refresh".equals(args[0]) && sender.isOp()) {
            Config.saveLastDayPrice(Config.getLatestPrice());
            Exchanger.autoBuySell();
            sender.sendMessage(MainClass.PREFIX + " 手动触发自动调价成功");
        } else if (args.length == 1 && "reload".equals(args[0]) && sender.isOp()) {
            MainClass.INSTANCE.reloadConfig();
            sender.sendMessage(MainClass.PREFIX + " 重载成功");
        } else {
            displayHelp(sender);
        }
        return true;
    }

    private void displayHelp(CommandSender sender) {
        sender.sendMessage(MainClass.PREFIX + " 交易票规则:");
        sender.sendMessage("1. 交易时间不会和现实一样受到限制，任意时间可交易");
        sender.sendMessage("2. 交易的股票数量必须是100的整数倍");
        sender.sendMessage("§7/dst all       §7获取股票§c§n全部§7持仓");
        sender.sendMessage("§7/dst price     §7获取股票§c§n实时§7价格");
        sender.sendMessage("§7/dst buy 数量   §7根据股票§c§n实时§7价格购买给定的数量,股数只能是100的整数倍");
        sender.sendMessage("§7/dst sell 数量  §7根据股票§c§n实时§7价格出售给定的数量,股数只能是100的整数倍");
        sender.sendMessage("§7");
    }

    private void displayAllHaveStock(CommandSender sender) {
        long count = Config.getAvailableStock(sender.getName());
        sender.sendMessage(MainClass.PREFIX + " §7你持有股票 §f" + Config.getStockName() + " §7总股数为 §a" + count + "§7股");
    }
}
